<template>
	<div class="upload-box" :style="{ height:fill ? '100%' : 'auto'}">

		<div class="img-upload" :style="{'width': fill ? '100%' : width+'px',height: fill ? '100%' : height+'px', border: fill ? 'none' : '1px dashed #d9d9d9'}">
			<div class="img-upload_area-sign">+</div>
			<div v-if="!uploadMore" class="img-upload_preview" :style='"background: url("+headerImage+") no-repeat center;"'></div>

			<input type="file" class="img-upload_input" @change="uploadImg" name="file" accept=".jpg,.jpeg,.png,.gif,.bmp,.tiff">

			<!--单张图时插槽-->
			<div v-if="!uploadMore">
				<slot name="del"></slot>
			</div>

		</div>
		<div v-if="model">
			<el-dialog title="图片裁剪" :visible.sync="model" width="80%" :close-on-click-modal='false'>
				<div class="model-show">
					<img id="image" :src="url" alt="">
				</div>
				<span slot="footer" class="dialog-footer">
					<el-button @click="model = false">取 消</el-button>
					<el-button type="primary" @click="model = false,confimImg()">确 定</el-button>
				</span>
			</el-dialog>
		</div>

		<el-progress v-if='uploadStart' type="circle" :percentage="percentage"></el-progress>
	</div>
</template>

<script>
	import Cropper from 'cropperjs'
	// import { UPLOAD } from '@/api/crm'

	export default {
		props: {
			width: {
				type: Number,
				default: 100
			},
			height: {
				type: Number,
				default: 100
			},
			headerImage: {
				type: String,
				default: ''
			},
			fileSize: Number,
			uploadMore: { //是否依次上传多张图，则本组件不显示上传图
				type: Boolean,
				default: false
			},
			fill: { //填充满，并去除边框
				type: Boolean,
				default: false
			},
			aspectRatio: { //是否开启截图比例
				type: Boolean,
				default: true
			},
			aspectRatioNum: { //上传宽高100*100，实际截图比例
				type: String,
				default: ''
			}
		},
		data() {
			return {
				model: false,
				modelSrc: '',
				url: '',
				cropper: '',
				croppable: false,
				//进度
				uploadStart: false,
				percentage: 0
			}
		},
		methods: {
			getObjectURL(file) {
				var url = null;
				if(window.createObjectURL != undefined) { // basic 
					url = window.createObjectURL(file);
				} else if(window.URL != undefined) { // mozilla(firefox) 
					url = window.URL.createObjectURL(file);
				} else if(window.webkitURL != undefined) { // webkit or chrome 
					url = window.webkitURL.createObjectURL(file);
				}
				return url;
			},
			uploadImg(e) {
				var _this = this;
				let files = e.target.files || e.dataTransfer.files;
				if(!files.length) return;
				this.model = true;
				this.$nextTick(() => {
					var image = document.getElementById('image');
					var inputImage = e.target
					if(_this.aspectRatio) {
						this.cropper = new Cropper(image, {
							aspectRatio: _this.aspectRatioNum ? _this.aspectRatioNum : _this.width / _this.height,
							autoCropArea: 1,
							ready: function() {
								_this.croppable = true;
							}
						});
					} else {
						this.cropper = new Cropper(image, {
							autoCropArea: 1,
							ready: function() {
								_this.croppable = true;
							}
						});
					}
					inputImage.value = '';
				})

				this.modelSrc = files[0];
				this.url = this.getObjectURL(this.modelSrc);
				//每次替换图片要重新得到新的url 
				if(this.cropper) {
					this.cropper.replace(this.url);
				}

				//初始化这个裁剪框 

			},
			confimImg() {
				this.model = false;
				var croppedCanvas;
				var roundedCanvas;
				if(!this.croppable) {
					return;
				}
				// Crop 
				croppedCanvas = this.cropper.getCroppedCanvas();

				// Round 
				roundedCanvas = this.getRoundedCanvas(croppedCanvas);
				this.postImg(roundedCanvas.toDataURL())

			},
			getRoundedCanvas(sourceCanvas) {
				var canvas = document.createElement('canvas');
				var context = canvas.getContext('2d');
				var width = sourceCanvas.width;
				var height = sourceCanvas.height;
				canvas.width = width;
				canvas.height = height;
				context.imageSmoothingEnabled = true;
				context.drawImage(sourceCanvas, 0, 0, width, height);
				context.globalCompositeOperation = 'destination-in';
				context.fill();
				return canvas;
			},
			dataURItoFile(dataurl) { // 转换图片 base64 => file 
				var arr = dataurl.split(','),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n);
				while(n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new Blob([u8arr], {
					type: mime
				});
			},
			async postImg(base64Img) { //图片上传
				let file = this.dataURItoFile(base64Img)
				let fileSize = this.fileSize || null
				const fileType = file.type.split('/')[1]
				const typeArray = ['gif', 'jpg', 'jpeg', 'png']
				if(!typeArray.includes(fileType)) {
					this.$message({
						message: '图片格式仅支持gif, jpg, jpeg,png',
						type: 'warning'
					});
					return false
				}

				if(fileSize && (file.size > fileSize * 1000 * 1024)) {
					this.$message({
						message: `图片大小不大于${fileSize}M`,
						type: 'warning'
					})
					return false
				}

				const fd = new FormData()
				fd.append('image_file', file)
				const xhr = new XMLHttpRequest()
				xhr.open('post', 'http://letaishop.dusnoob.com/api/v1/upload/image', true)
				
				const token = localStorage.getItem('access_token')
				
				xhr.setRequestHeader('Authorization', 'Bearer ' + token)
				//进度获取
				this.percentage = 0
				this.uploadStart = true
				xhr.upload.onprogress = (e) => {
					var percent = e.loaded / e.total * 100;
					var percentStr = String(percent);
					if(percentStr == "100") {
						percentStr = "100.0";
					}
					percentStr = percentStr.substring(0, percentStr.indexOf("."));
					this.percentage = +percentStr
				}

				//上传状态
				xhr.addEventListener('load', (e) => {
					if(e.target.status !== 200) {
						return
					}
					if(e.target.status === 200) {
						console.log(e, 2233)
						this.$emit('update:headerImage', JSON.parse(e.target.response).url)
						this.uploadStart = false
					}
				}, false)
				xhr.send(fd)
					

			}
		}

	}
</script>

<style lang="scss">
	.upload-box {
		position: relative;
		input[type="file"] {
			display: block!important;
		}
		.img-upload {
			width: 100px;
			height: 100px;
			border: 1px dashed #d9d9d9;
			border-radius: 4px;
			cursor: pointer;
			position: relative;
			&:hover {
				border: 1px dashed #1E9FFF;
			}
			&_area-sign {
				width: 20px;
				height: 20px;
				text-align: center;
				line-height: 20px;
				transform: scale(2);
				position: absolute;
				top: 0;
				bottom: 0;
				left: 0;
				right: 0;
				margin: auto;
				color: #8C939D;
			}
			&_preview {
				width: 100%;
				height: 100%;
				position: absolute;
				top: 0;
				left: 0;
				background-repeat: no-repeat;
				background-position: center;
				background-size: cover!important;
			}
			&_input {
				width: 100%;
				height: 100%;
				opacity: 0;
				cursor: pointer;
				position: absolute;
				top: 0;
				left: 0;
			}
		}
		.el-progress {
			position: absolute;
			top: 0;
			left: 0;
			width: 100px;
			height: 100px;
		}
		.el-progress-circle {
			padding: 20px;
			height: 100px!important;
			width: 100px!important;
			background: #FFFFFF;
			border: 1px dashed #d9d9d9;
			box-sizing: border-box;
		}
		.model-show {
			height: 500px;
			overflow: hidden;
		}
		.cropper-container {
			direction: ltr;
			font-size: 0;
			line-height: 0;
			position: relative;
			-ms-touch-action: none;
			touch-action: none;
			-webkit-user-select: none;
			-moz-user-select: none;
			-ms-user-select: none;
			user-select: none;
		}
		.cropper-container img {
			/*Avoid margin top issue (Occur only when margin-top <= -height)
 */
			display: block;
			height: 100%;
			image-orientation: 0deg;
			max-height: none !important;
			max-width: none !important;
			min-height: 0 !important;
			min-width: 0 !important;
			width: 100%;
		}
		.cropper-wrap-box,
		.cropper-canvas,
		.cropper-drag-box,
		.cropper-crop-box,
		.cropper-modal {
			bottom: 0;
			left: 0;
			position: absolute;
			right: 0;
			top: 0;
		}
		.cropper-wrap-box,
		.cropper-canvas {
			overflow: hidden;
		}
		.cropper-drag-box {
			background-color: #fff;
			opacity: 0;
		}
		.cropper-modal {
			background-color: #000;
			opacity: .5;
		}
		.cropper-view-box {
			display: block;
			height: 100%;
			outline-color: rgba(51, 153, 255, 0.75);
			outline: 1px solid #39f;
			overflow: hidden;
			width: 100%;
		}
		.cropper-dashed {
			border: 0 dashed #eee;
			display: block;
			opacity: .5;
			position: absolute;
		}
		.cropper-dashed.dashed-h {
			border-bottom-width: 1px;
			border-top-width: 1px;
			height: 33.33333%;
			left: 0;
			top: 33.33333%;
			width: 100%;
		}
		.cropper-dashed.dashed-v {
			border-left-width: 1px;
			border-right-width: 1px;
			height: 100%;
			left: 33.33333%;
			top: 0;
			width: 33.33333%;
		}
		.cropper-center {
			display: block;
			height: 0;
			left: 50%;
			opacity: .75;
			position: absolute;
			top: 50%;
			width: 0;
		}
		.cropper-center:before,
		.cropper-center:after {
			background-color: #eee;
			content: ' ';
			display: block;
			position: absolute;
		}
		.cropper-center:before {
			height: 1px;
			left: -3px;
			top: 0;
			width: 7px;
		}
		.cropper-center:after {
			height: 7px;
			left: 0;
			top: -3px;
			width: 1px;
		}
		.cropper-face,
		.cropper-line,
		.cropper-point {
			display: block;
			height: 100%;
			opacity: .1;
			position: absolute;
			width: 100%;
		}
		.cropper-face {
			background-color: #fff;
			left: 0;
			top: 0;
		}
		.cropper-line {
			background-color: #39f;
		}
		.cropper-line.line-e {
			cursor: ew-resize;
			right: -3px;
			top: 0;
			width: 5px;
		}
		.cropper-line.line-n {
			cursor: ns-resize;
			height: 5px;
			left: 0;
			top: -3px;
		}
		.cropper-line.line-w {
			cursor: ew-resize;
			left: -3px;
			top: 0;
			width: 5px;
		}
		.cropper-line.line-s {
			bottom: -3px;
			cursor: ns-resize;
			height: 5px;
			left: 0;
		}
		.cropper-point {
			background-color: #39f;
			height: 5px;
			opacity: .75;
			width: 5px;
		}
		.cropper-point.point-e {
			cursor: ew-resize;
			margin-top: -3px;
			right: -3px;
			top: 50%;
		}
		.cropper-point.point-n {
			cursor: ns-resize;
			left: 50%;
			margin-left: -3px;
			top: -3px;
		}
		.cropper-point.point-w {
			cursor: ew-resize;
			left: -3px;
			margin-top: -3px;
			top: 50%;
		}
		.cropper-point.point-s {
			bottom: -3px;
			cursor: s-resize;
			left: 50%;
			margin-left: -3px;
		}
		.cropper-point.point-ne {
			cursor: nesw-resize;
			right: -3px;
			top: -3px;
		}
		.cropper-point.point-nw {
			cursor: nwse-resize;
			left: -3px;
			top: -3px;
		}
		.cropper-point.point-sw {
			bottom: -3px;
			cursor: nesw-resize;
			left: -3px;
		}
		.cropper-point.point-se {
			bottom: -3px;
			cursor: nwse-resize;
			height: 20px;
			opacity: 1;
			right: -3px;
			width: 20px;
		}
		@media (min-width: 768px) {
			.cropper-point.point-se {
				height: 15px;
				width: 15px;
			}
		}
		@media (min-width: 992px) {
			.cropper-point.point-se {
				height: 10px;
				width: 10px;
			}
		}
		@media (min-width: 1200px) {
			.cropper-point.point-se {
				height: 5px;
				opacity: .75;
				width: 5px;
			}
		}
		.cropper-point.point-se:before {
			background-color: #39f;
			bottom: -50%;
			content: ' ';
			display: block;
			height: 200%;
			opacity: 0;
			position: absolute;
			right: -50%;
			width: 200%;
		}
		.cropper-invisible {
			opacity: 0;
		}
		.cropper-bg {
			background-image: url('');
		}
		.cropper-hide {
			display: block;
			height: 0;
			position: absolute;
			width: 0;
		}
		.cropper-hidden {
			display: none !important;
		}
		.cropper-move {
			cursor: move;
		}
		.cropper-crop {
			cursor: crosshair;
		}
		.cropper-disabled .cropper-drag-box,
		.cropper-disabled .cropper-face,
		.cropper-disabled .cropper-line,
		.cropper-disabled .cropper-point {
			cursor: not-allowed;
		}
	}
</style>